package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.result.Result;
import com.itheima.health.util.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 *
 * @Author itcast
 * @Create 2023/4/22
 **/
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile file){
        log.info("文件上传：{}",file);

        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + extension;

        try {
            String filePath = aliOssUtil.upload(file.getBytes(), name);
            return new Result(true,MessageConst.PIC_UPLOAD_SUCCESS,filePath);
        } catch (IOException e) {
            log.error("文件上传失败");
        }

        return new Result(false,MessageConst.PIC_UPLOAD_FAIL);
    }
}
